<template>
  <view class="available-orders">
    <!-- 分类筛选 -->
    <view class="category-filter">
      <scroll-view scroll-x class="filter-scroll">
        <view 
          v-for="(category, index) in categories" 
          :key="index"
          class="filter-item"
          :class="{ active: activeCategoryId === category.id }"
          @click="handleCategoryChange(category.id)"
        >
          <text class="icon">{{ category.icon }}</text>
          <text class="name">{{ category.name }}</text>
        </view>
      </scroll-view>
    </view>

    <!-- 订单列表 -->
    <scroll-view 
      scroll-y 
      class="order-list"
      @scrolltolower="handleLoadMore"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="handleRefresh"
    >
      <!-- 空状态 -->
      <view v-if="orderList.length === 0 && !loading" class="empty-state">
        <view class="empty-icon">🔍</view>
        <view class="empty-text">暂无可接订单</view>
        <view class="empty-hint">刷新试试或等待新订单</view>
      </view>

      <!-- 订单卡片 -->
      <view 
        v-for="order in orderList" 
        :key="order.id"
        class="order-card"
      >
        <!-- 头部 -->
        <view class="card-header">
          <view class="left">
            <text class="icon">{{ getCategoryIcon(order.categoryName) }}</text>
            <text class="name">{{ order.categoryName }}</text>
          </view>
          <!-- <view class="earning">💰 ¥{{ order.riderEarning }}</view> -->
          <view class="earning">💰 ¥{{ order.totalAmount }}</view>
        </view>

        <!-- 地址信息 -->
        <view class="address-info">
          <view class="address-item">
            <view class="label">
              <text class="icon">📍</text>
              <text>取件</text>
            </view>
            <view class="value">{{ order.pickupAddress }}</view>
          </view>
          <view class="divider"></view>
          <view class="address-item">
            <view class="label">
              <text class="icon">🏠</text>
              <text>送达</text>
            </view>
            <view class="value">{{ order.deliveryAddress }}</view>
          </view>
        </view>

        <!-- 订单信息 -->
        <view class="order-meta">
          <view class="meta-item" v-if="order.pickupCode">
            <text class="label">取件码:</text>
            <text class="value">{{ order.pickupCode }}</text>
          </view>
          <view class="meta-item" v-if="order.pickupRemark">
            <text class="label">备注:</text>
            <text class="value">{{ order.pickupRemark }}</text>
          </view>
          <view class="meta-item">
            <text class="label">发布时间:</text>
            <text class="value time">{{ getRelativeTime(order.createTime) }}</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="card-actions">
          <button class="btn-detail" @click="handleViewDetail(order)">查看详情</button>
          <button class="btn-accept" @click="handleAccept(order)">立即接单</button>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="loading" class="loading-more">加载中...</view>
      <view v-else-if="!hasMore && orderList.length > 0" class="no-more">没有更多了</view>
    </scroll-view>
  </view>
</template>

<script>
import { getAvailableOrders, acceptOrder, getCategoryList } from '@/api/pickup'

export default {
  data() {
    return {
      activeCategoryId: null,
      categories: [
        { id: null, icon: '📋', name: '全部' }
      ],
      orderList: [],
      loading: false,
      refreshing: false,
      hasMore: true,
      page: {
        current: 1,
        size: 10
      }
    }
  },
  onLoad() {
    this.loadCategories()
    this.loadOrderList()
  },
  methods: {
    // 加载分类列表
    async loadCategories() {
      try {
        const categoryList = await getCategoryList()
        this.categories = [
          { id: null, icon: '📋', name: '全部' },
          ...categoryList.map(item => ({
            id: item.id,
            icon: item.icon,
            name: item.name
          }))
        ]
      } catch (error) {
        console.error('加载分类失败:', error)
      }
    },

    // 加载订单列表
    async loadOrderList(refresh = false) {
      if (this.loading) return
      
      if (refresh) {
        this.page.current = 1
        this.hasMore = true
        this.orderList = []
      }

      try {
        this.loading = true
        const params = {
          current: this.page.current,
          size: this.page.size
        }
        
        // 只有当 categoryId 不为 null 时才添加
        if (this.activeCategoryId !== null) {
          params.categoryId = this.activeCategoryId
        }
        
        const pageData = await getAvailableOrders(params)
        
        if (refresh) {
          this.orderList = pageData.records
        } else {
          this.orderList = [...this.orderList, ...pageData.records]
        }
        
        this.hasMore = this.page.current < pageData.pages
      } catch (error) {
        console.error('加载订单失败:', error)
        uni.showToast({ title: error.msg || '加载失败', icon: 'none' })
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },

    // 分类切换
    handleCategoryChange(categoryId) {
      this.activeCategoryId = categoryId
      this.loadOrderList(true)
    },

    // 下拉刷新
    handleRefresh() {
      this.refreshing = true
      this.loadOrderList(true)
    },

    // 加载更多
    handleLoadMore() {
      if (this.hasMore && !this.loading) {
        this.page.current++
        this.loadOrderList()
      }
    },

    // 查看详情
    handleViewDetail(order) {
      // 构建详情内容
      let content = `取件: ${order.pickupAddress}\n\n送达: ${order.deliveryAddress}`
      
      if (order.pickupCode) {
        content += `\n\n取件码: ${order.pickupCode}`
      }
      
      if (order.pickupRemark) {
        content += `\n\n备注: ${order.pickupRemark}`
      }
      
      content += `\n\n订单金额: ¥${order.totalAmount}`
      content += `\n发布时间: ${this.getRelativeTime(order.createTime)}`
      
      uni.showModal({
        title: '订单详情',
        content: content,
        confirmText: '我要接单',
        cancelText: '关闭',
        success: (res) => {
          if (res.confirm) {
            // 直接执行接单操作
            this.doAcceptOrder(order)
          }
        }
      })
    },

    // 接单（点击立即接单按钮，需要确认）
    handleAccept(order) {
      uni.showModal({
        title: '确认接单',
        content: `订单金额: ¥${order.totalAmount}\n确定接这个订单吗？接单后请尽快完成任务。`,
        success: async (res) => {
          if (res.confirm) {
            await this.doAcceptOrder(order)
          }
        }
      })
    },

    // 执行接单操作
    async doAcceptOrder(order) {
      try {
        uni.showLoading({ title: '接单中...' })
        await acceptOrder(order.id)
        uni.hideLoading()
        
        uni.showModal({
          title: '接单成功',
          content: '请尽快前往取件地点',
          showCancel: false,
          success: () => {
            // 跳转到订单详情
            uni.redirectTo({
              url: `/pages/pickup/detail?orderId=${order.id}`
            })
          }
        })
      } catch (error) {
        uni.hideLoading()
        uni.showToast({ title: error.msg || '接单失败', icon: 'none' })
      }
    },

    // 获取分类图标
    getCategoryIcon(categoryName) {
      const iconMap = {
        '取外卖': '🍱',
        '取快递': '📦',
        '取咖啡': '☕',
        '代买': '🛒',
        '其他服务': '🐰'
      }
      return iconMap[categoryName] || '📦'
    },

    // 获取相对时间
    getRelativeTime(timeStr) {
      const time = new Date(timeStr).getTime()
      const now = new Date().getTime()
      const diff = now - time
      
      const minute = 60 * 1000
      const hour = 60 * minute
      const day = 24 * hour
      
      if (diff < minute) {
        return '刚刚发布'
      } else if (diff < hour) {
        return `${Math.floor(diff / minute)}分钟前发布`
      } else if (diff < day) {
        return `${Math.floor(diff / hour)}小时前发布`
      } else {
        return `${Math.floor(diff / day)}天前发布`
      }
    }
  }
}
</script>

<style scoped>
.available-orders {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #F5F5F5;
}

.category-filter {
  background: #fff;
  padding: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.filter-scroll {
  white-space: nowrap;
}

.filter-item {
  display: inline-block;
  padding: 16rpx 32rpx;
  margin-right: 16rpx;
  background: #F8F9FA;
  border-radius: 32rpx;
  font-size: 26rpx;
}

.filter-item.active {
  background: linear-gradient(135deg, #4ECDC4, #44A08D);
  color: #fff;
}

.filter-item .icon {
  margin-right: 8rpx;
}

.order-list {
  flex: 1;
  padding: 24rpx;
}

.empty-state {
  padding: 200rpx 0;
  text-align: center;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.empty-hint {
  font-size: 24rpx;
  color: #999;
}

.order-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.card-header .left {
  display: flex;
  align-items: center;
}

.card-header .icon {
  font-size: 40rpx;
  margin-right: 12rpx;
}

.card-header .name {
  font-size: 32rpx;
  font-weight: bold;
}

.card-header .earning {
  font-size: 32rpx;
  font-weight: bold;
  color: #FF6B6B;
}

.address-info {
  background: #F8F9FA;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
}

.address-item {
  display: flex;
  margin-bottom: 20rpx;
}

.address-item:last-child {
  margin-bottom: 0;
}

.address-item .label {
  display: flex;
  align-items: center;
  min-width: 100rpx;
  font-size: 26rpx;
  color: #666;
}

.address-item .label .icon {
  margin-right: 8rpx;
}

.address-item .value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.divider {
  height: 1rpx;
  background: #E0E0E0;
  margin: 20rpx 0;
}

.order-meta {
  margin-bottom: 24rpx;
}

.meta-item {
  display: flex;
  margin-bottom: 12rpx;
  font-size: 24rpx;
}

.meta-item:last-child {
  margin-bottom: 0;
}

.meta-item .label {
  color: #999;
  min-width: 120rpx;
}

.meta-item .value {
  flex: 1;
  color: #666;
}

.meta-item .time {
  color: #4ECDC4;
}

.card-actions {
  display: flex;
  gap: 16rpx;
}

.card-actions button {
  flex: 1;
  height: 72rpx;
  font-size: 28rpx;
  border-radius: 36rpx;
  border: none;
}

.btn-detail {
  background: #F5F5F5;
  color: #666;
}

.btn-accept {
  background: linear-gradient(135deg, #4ECDC4, #44A08D);
  color: #fff;
  font-weight: bold;
}

.loading-more,
.no-more {
  text-align: center;
  padding: 32rpx;
  font-size: 24rpx;
  color: #999;
}
</style>

